# -*- coding: UTF-8 -*-
import logging.config, os, sys
import xbmc, xbmcgui, xbmcplugin
configRoot = os.path.join(os.getcwd(), "resources", "logging.conf")
try:
  logging.config.fileConfig(configRoot)
except:
  logging.basicConfig()
  logging.getLogger('root').exception('Failed to initialize logging... falling back to defaults.')

# Add the lib dir to path  
sys.path.append(os.path.join(os.getcwd(), 'lib'))

from utils.pluginsupport import parseArguments, play, list
from tvshack import TVShackHandler

log = logging.getLogger("root")
#log.info("calling with args: %s"%str(sys.argv))

params = parseArguments(sys.argv[2])
tvshackHandler = TVShackHandler()
if tvshackHandler.isAction(params):
  log.info("Running action")
  tvshackHandler.execute(params)
else:
  items, contentType, playable = tvshackHandler.handle(params)
  if playable:
    try:
      play(items)
    except Exception, e:
      log.exception("Failed to play items!")
      xbmcgui.Dialog().ok("Failed to play items", str(e))
  else:
    try:
      list(items)
    except Exception, e:
      log.exception("Script failed listing items!")
      xbmcgui.Dialog().ok("Failed to list items", str(e))
      xbmcplugin.endOfDirectory(int(sys.argv[1]), False, cacheToDisc=False)
    else: 
      if contentType:
        log.warn("Setting content type: " + str(contentType))
        xbmcplugin.setContent(int(sys.argv[1]), contentType)
      log.warn("Script finished, success!")
      xbmcplugin.endOfDirectory(int(sys.argv[1]))
